<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImg"
    :on-success="handleAvatarSuccess"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <el-progress v-if="isShow" type="circle" :percentage="percentage" class="progress" />
  </el-upload>
</template>

<script>
const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDtfJk3BAyazDF9qOiqlTzXyHOI0Xs20lJ', // id
  SecretKey: 'OZYUFnAKG3e4HI7kDTWN1SghU4RbXFk1'// 秘钥
})
export default {
  data() {
    return {
      imageUrl: '', // 图片地址
      percentage: 0, // 进度条占比
      isShow: false// 是否显示进度条
    }
  },
  methods: {
    // 自定义上传行为
    uploadImg(res) {
      // 进度条显示
      this.isShow = true
      cos.putObject({
        Bucket: 'smy-1306621493', /* 必须 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: res.file.name, /* 必须 文件名*/
        StorageClass: 'STANDARD', // 标准模式
        Body: res.file, // 上传文件对象
        onProgress: (progressData) => { // 进度条
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        // 如果没有错误,且成功
        if (err === null && data.statusCode === 200) {
          this.imageUrl = `https:${data.Location}`
        }
        // 进度条消失
        this.isShow = false
      }
      )
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    }
  }
}
</script>

<style>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
